//
//  CarShowImageCell.swift
//  koolcar
//
//  Created by kuaimaxiansheng on 2023/10/17.
//

import UIKit
import FSPagerView

class CarShowImageCell: FSPagerViewCell {
    var bgImgeView: UIImageView!
    var bgVrView: UIView!
    var layout = UICollectionViewFlowLayout()
    var collectionView: UICollectionView!
    var contentModel: CarDetailsContentModel!
    var vrImage: UIImage!
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.initUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    func initUI(){
        
        self.bgImgeView = UIImageView(frame: CGRect(x: 30, y: (kScreenHeight - 366)/2, width: kScreenWidth - 60, height: 366))
        self.bgImgeView.isUserInteractionEnabled = true
        self.contentView.addSubview(self.bgImgeView)
        
        
        self.bgVrView = UIView(frame: .zero)
        self.bgVrView.backgroundColor = .black
        self.bgVrView.alpha = 0.6
        self.bgImgeView.addSubview(self.bgVrView)
        
        layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        let ww = (kScreenWidth - 76)/3
        layout.itemSize = CGSize(width:ww, height: 40)
        
        self.collectionView = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: layout)
        self.collectionView.register(VrCollectionViewCell.self, forCellWithReuseIdentifier: "VrCollectionViewCell")
        self.collectionView.delegate = self
        self.collectionView.dataSource = self
        self.collectionView.backgroundColor = .clear
//        self.collectionView.contentInset = UIEdgeInsets.init(top: 0, left: 20, bottom: 0, right: 20)
        self.collectionView.isScrollEnabled = false
        self.bgVrView.addSubview(self.collectionView)
        
        
        
        
        self.bgImgeView.snp.makeConstraints { make in
            make.top.equalTo(0)
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.height.equalTo(280)
            make.bottom.equalTo(0)
        }
        
        self.bgVrView.snp.makeConstraints { make in
            make.left.equalTo(38)
            make.right.equalTo(-38)
            make.height.equalTo(40)
            make.bottom.equalTo(0)
        }
        
        self.layoutIfNeeded()
        self.bgVrView.roundCorners(corners: UIRectCorner(arrayLiteral: [.topLeft,.topRight]), radius: 20)
        self.collectionView.snp.makeConstraints { make in
            make.top.equalTo(0)
            make.left.equalTo(0)
            make.right.equalTo(-0)
            make.height.equalTo(40)
        }
        
        
    }
    
    //Model
    func setContentModel(contentModel: CarDetailsContentModel){
        self.contentModel = contentModel
        
        let ww = (kScreenWidth - 76)/Int(contentModel.videoVrPdfList?.count ?? 0)
        layout.itemSize = CGSize(width:ww, height: 40)
        
        self.bgVrView.snp.updateConstraints { make in
            make.height.equalTo(40)
        }
        
        self.collectionView.snp.updateConstraints { make in
            make.height.equalTo(40)
        }
        
        
        if contentModel.videoVrPdfList?.count == 0{
            self.bgVrView.snp.updateConstraints { make in
                make.height.equalTo(0)
            }
            
            self.collectionView.snp.updateConstraints { make in
                make.height.equalTo(40)
            }
        }
        
        self.collectionView.reloadData()
        self.updateConstraints()
    }
    
    
}

extension CarShowImageCell: UICollectionViewDelegate,UICollectionViewDataSource ,UICollectionViewDelegateFlowLayout{
    
    //    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    //        var tempWidth = 70
    //        if self.dataArray.count > indexPath.row{
    //            let titileStr = dataArray[indexPath.row]
    //            tempWidth = Int(XTManageCenter.getLabWidth(labelStr: titileStr, font: UIFont.init(name: Theme.PingFangSCRegular, size: 12)!, height: 37))
    //            return CGSize.init(width: tempWidth + 35, height: 37)
    //        }
    //        return CGSize.init(width: tempWidth, height: 37)
    //    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return (self.contentModel?.videoVrPdfList ?? []).count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "VrCollectionViewCell", for: indexPath) as! VrCollectionViewCell
        let dataArray =  self.contentModel?.videoVrPdfList ?? []
        if dataArray.count > indexPath.row{
            let model = dataArray[indexPath.row]
            cell.titleBtn.setImage(UIImage(named: model.image ?? ""), for: .normal)
            cell.titleBtn.setTitle(model.name ?? "", for: .normal)
        }
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let dataArray =  self.contentModel?.videoVrPdfList ?? []
        if dataArray.count > indexPath.row{
            let model = dataArray[indexPath.row]
            switch model.type {
            case 0://视频
                let vc = VideoViewController()
                vc.titleStr = model.name ?? ""
                vc.videoUrl = model.content ?? ""
                self.viewController().navigationController?.pushViewController(vc, animated: true)
            case 1://VR
                self.vrImageViewBtnAntion(model: model)
            default://pdf
                let vc = WebViewController()
                vc.urlStr = model.content ?? ""
                vc.titleStr = model.name ?? ""
                self.viewController().navigationController?.pushViewController(vc, animated: true)
            }
        }
    }
  
    
    
    //360查看图片 传入vr的image
    func vrImageViewBtnAntion(model: VideoVRPdfModel) {
        //纹理图test 连接 https://xt-temp.oss-cn-shenzhen.aliyuncs.com/Store/2022-03-02/1646211119878.jpg
//        guard let aUrl = URL.init(string: model.content ?? "") else {
//            return
//        }
//
//        if self.vrImage == nil {
//            DispatchQueue.global().async {
//                URLSession.shared.dataTask(with: aUrl) { imgData, urlReponse, err in
//                    guard imgData != nil, let img = UIImage.init(data: imgData!) else {
//                        return
//                    }
//                    self.vrImage = img
//                    DispatchQueue.main.async {
//                        let vc = PanoramaBrowserViewController()
//                        vc.vrImage = self.cropImageToBars(image: img)
//                        self.currentViewController()?.navigationController?.pushViewController(vc, animated: true)
//                    }
//                }.resume()
//            }
//        }else{
//            let vc = PanoramaBrowserViewController()
//            vc.vrImage = self.cropImageToBars(image: self.vrImage)
//            self.currentViewController()?.navigationController?.pushViewController(vc, animated: true)
//        }
        
        let vc = WebViewController()
        var language = "tc"//繁体  (注：h5里用的是tc, app里用的是cn)
        let localSet = XTManageCenter.getLocalStringDataValue(aKey: UtilCenter.kAppLanguage)
        if localSet.contains("en") {
            language = "en"// 英文
        }else if localSet.contains("zh-Hans") {
            language = "sc"//简体
        }
        vc.urlStr = String(format: "%@/%@/cardetail/localcar/%d", ServerConfig.requestH5Url(), language, self.contentModel.id ?? 0)
        vc.vrWebFlag = true
        self.currentViewController()?.navigationController?.pushViewController(vc, animated: true)
    }
    
    ///需要比例1：2  或   2：1
    func cropImageToBars(image: UIImage) -> UIImage {
        var ww: CGFloat = image.size.width
        var hh: CGFloat = image.size.height
        let pre: CGFloat = hh/ww
        
        if ww.truncatingRemainder(dividingBy: 2) != 0 {
            ww = ww + 1
        }
        if ww.truncatingRemainder(dividingBy: 2) != 0 {
            hh = hh + 1
        }
        
        if ww > 2048 {
            ww = 2048
            hh = pre * 2048
        }
        
        if hh > 2048 {
            hh = 2048
            ww = 2048/pre
        }
        
        
        if pre > 0.5 {
            hh = ww/2
        }else if pre < 0.5 {
            ww = hh * 2
        }
        if hh < ww && hh < 1024 {
            hh = 1024
            ww = hh * 2
        }else if ww < hh && ww < 1024 {
            ww = 1024
            hh = ww * 2
        }
        let rect = CGRect.init(x: 0, y: 0, width: ww, height: hh)
        UIGraphicsBeginImageContextWithOptions(rect.size, false, 1.0)
        image.draw(in: rect)
        guard let newImage = UIGraphicsGetImageFromCurrentImageContext() else { return UIImage.init() }
        UIGraphicsEndImageContext()
        return newImage
    }
    
    
}

class VrCollectionViewCell: UICollectionViewCell {
    var titleBtn: UIButton!
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.clipsToBounds = true
        
        self.titleBtn = UIButton(frame: .zero)
        self.titleBtn.titleLabel?.font = UIFont(name: Theme.PingFangSCRegular, size: 12)
        self.titleBtn.setTitleColor(.white, for: .normal)
        self.titleBtn.isUserInteractionEnabled = false
        self.titleBtn.titleEdgeInsets = UIEdgeInsets(top: 0, left: 4, bottom: 0, right: 0)
        self.contentView.addSubview(self.titleBtn)
     
        
        self.titleBtn.snp.makeConstraints { make in
            make.top.equalTo(0)
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.height.equalTo(40)
            make.bottom.equalTo(0)
        }
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

